package com.gee.spring.cloud.feign.flow.work.impl;

import com.gee.spring.cloud.feign.flow.exception.SkippedException;
import com.gee.spring.cloud.feign.flow.execute.ExecuteContext;
import com.gee.spring.cloud.feign.flow.handler.DefaultWorkHandler;
import com.gee.spring.cloud.feign.flow.result.ExecuteState;
import com.gee.spring.cloud.feign.flow.result.WorkResult;
import com.gee.spring.cloud.feign.flow.work.AbstractWork;

import java.lang.reflect.Method;
import java.util.concurrent.CountDownLatch;

/**
 * desc:
 *
 * @author gee wrote on  2021-01-14 20:09:09
 */
public class EndWork extends AbstractWork<Object> {

    public static final String END_WORK_ID = "endWork";

    private CountDownLatch countDownLatch;

    private EndWork() {
    }

    @Override
    public void accept(ExecuteContext executeContext, Throwable throwable) {
        getWorkHandler().handleBeforeBegin(this, executeContext);
        getWorkHandler().handleAfterFinish(this, executeContext);
        executeContext.setPreFUSWorkId(getWorkExecuteProperties().getPreFUSWorkId().get());
        executeContext.getWorkResultMap().remove(getId());
        executeContext.getWorkResultMap().remove(InitWork.INIT_WORK_ID);
        executeContext.getGlobalExecuteState().compareAndSet(ExecuteState.WORKING.getCode(), ExecuteState.SUCCESSFUL.getCode());
        countDownLatch.countDown();
    }

    @Override
    public Object process(Object target, Method method, Object[] args) throws Exception {
        return null;
    }

    @Override
    public String getId() {
        return EndWork.END_WORK_ID;
    }

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    public CountDownLatch getCountDownLatch() {
        return countDownLatch;
    }

    public void trySkipPrevious(SkippedException skippedException, ExecuteContext executeContext){
        WorkResult<?> workResult = executeContext.getWorkResult(this.getId());
        workResult.getExecuteState().set(3);
        workResult.setException(skippedException);
        getWorkHandler().trySkipPrevious(this, skippedException, executeContext);
    }

    public static  EndWork build(){
        EndWork endWork = new EndWork();
        endWork.setWorkHandler(new DefaultWorkHandler());
        return endWork;
    }
}
